using System;
using System.Collections.Generic;
using System.Linq;
using AutoInjector.Editor;
using EasyEditorGUI.Editor;
using UnityEditor;
using UnityEngine;

namespace EasyLocalization.Editor
{
    [CustomPropertyDrawer(typeof(LocalizationKeyAttribute))]
    public class LocalizationKeyDrawer : PropertyDrawer
    {
        Rect _tmpRect;
        LocalizationDictionary _dic;
        LocalizationDictionary GetDic(SerializedProperty sp)
        {
            if (_dic == null)
            {
                var attr = attribute as LocalizationKeyAttribute;
                if (attr.dictionaryFromOtherFields)
                {
                    var iter = sp.serializedObject.GetIterator();
                    iter.NextVisible(true);
                    while (iter.NextVisible(false))
                    {
                        if (iter.propertyType == SerializedPropertyType.ObjectReference &&
                            iter.objectReferenceValue != null &&
                            iter.objectReferenceValue is LocalizationDictionary dic)
                        {
                            _dic = dic;
                            break;
                        }
                    }
                }
                else
                {
                    _dic = Finder.SearchInProject<LocalizationDictionary>(attr.dictionaryName);
                }
                
                if (!_dic.isReady)
                {
                    _dic.LoadAsync().GetAwaiter().GetResult();
                }
            }

            return _dic;
        }
        
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            if (property.propertyType != SerializedPropertyType.String)
            {
                return;
            }
            
            EditorGUI.LabelField(position, label);
            position.x += EditorGUIUtility.labelWidth;
            position.width -= EditorGUIUtility.labelWidth;

            var dic = GetDic(property);
            if (GUI.Button(position, dic[property.stringValue], EditorStyles.popup))
            {
                var options = dic.keys.Select(x => $"{FormatKeyString(x)} : {dic[x]}");
                var dropdownWin = new DropDownWinWithAddBtn(new Vector2(_tmpRect.width, 200), options, dic);
                dropdownWin.onSelectionChanged += index =>
                {
                    property.stringValue = dic.keys.ElementAt(index);
                    property.serializedObject.ApplyModifiedProperties();
                };
                dropdownWin.Show(_tmpRect);
            }
            if (Event.current.type == EventType.Repaint) _tmpRect = position;
        }

        string FormatKeyString(string key)
        {
            return key.Length > 7 ? key.Substring(0, 7) : key;
        }

        class DropDownWinWithAddBtn : DropDownWindow 
        {
            readonly LocalizationDictionary _dic;

            public DropDownWinWithAddBtn(Vector2 size, IEnumerable<string> items, LocalizationDictionary dic) 
                : base(size, items)
            {
                _dic = dic;
            }

            protected override void RenderToolbar()
            {
                base.RenderToolbar();
                if (GUILayout.Button("+", EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)) &&
                    !string.IsNullOrEmpty(_listView.searchString))
                {
                    _dic[Guid.NewGuid().ToString("N")] = _listView.searchString;
                    _dic.Save();
                    
                    _listView.Reload();
                }
            }
        }
    }
}